<route lang="json5" type="page">
{
  layout: 'default',
  style: {
    navigationBarTitleText: '节目库',
  },
}
</route>

<script setup>
import BottomOperateBox from '@/components/BottomOperateBox.vue'
import ContentBox from '@/components/ContentBox.vue'
import CommonActivityItem from '@/components/CommonActivityItem.vue'
import { uniNavigateTo } from '@/utils'
import ProgrammeApi from '@/service/programme'
import ProgrammeItem from '@/components/ProgrammeItem.vue'
import { useSelectedProgrammeStore } from '@/store/selectedProgramme'
import { MAX_PROGRAMME_COUNT } from '@/configs/constant'

const {
  addSelectedProgramme,
  removeSelectedProgramme,
  setSelectedProgrammeList,
  clearSelectedProgrammeList,
} = useSelectedProgrammeStore()

const _selectedProgrammeList = computed(() => {
  console.log('useSelectedProgrammeStore', useSelectedProgrammeStore())
  const sList = useSelectedProgrammeStore().selectedProgrammeList
  if (sList?.length) {
    return sList.map((item) => item.id)
  }
  return []
})

const toggleSelectItem = (item) => {
  if (_selectedProgrammeList.value.includes(item.id)) {
    removeSelectedProgramme(item)
  } else {
    addSelectedProgramme(item)
  }
}

const isSelectedAll = computed(() => {
  const selectedList = _selectedProgrammeList.value.length
  return (
    selectedList === scrollState.dataList.length ||
    selectedList === MAX_PROGRAMME_COUNT
  )
})

const toggleSelectAll = () => {
  if (isSelectedAll.value) {
    clearSelectedProgrammeList()
  } else {
    // 设置 scrollState.dataList 的前 MAX_PROGRAMME_COUNT 个为选中
    setSelectedProgrammeList(scrollState.dataList.slice(0, MAX_PROGRAMME_COUNT))
  }
}

const handleNext = () => {
  uni.navigateBack()
}

/** ----------- 分页加载 start --------- */
const pageObj = ref({
  pageNo: 1,
  pageSize: MAX_PROGRAMME_COUNT,
})
const scrollState = reactive({
  refresherTriggered: false,
  dataList: [],
  loadState: 'loading',
})

const getDataList = async () => {
  if (scrollState.loadState === 'finished') return
  try {
    const params = {
      ...pageObj.value,
      column: 'createTime',
      order: 'desc',
    }
    const { code, result } = await ProgrammeApi.getProgrammePage(params)
    if (code === 200 && result) {
      const { records, pages } = result
      if (records?.length) {
        scrollState.dataList = [...scrollState.dataList, ...records]
      }
      if (pageObj.value.pageNo < pages) {
        pageObj.value.pageNo++
      } else {
        scrollState.loadState = 'finished'
      }
    } else {
      scrollState.loadState = 'error'
    }
  } catch (e) {
    scrollState.loadState = 'error'
  }
}

const reset = () => {
  pageObj.value.pageNo = 1
  scrollState.dataList = []
  scrollState.loadState = 'loading'
}

const onRefresherrefresh = async () => {
  scrollState.refresherTriggered = true
  await refreshList()
  scrollState.refresherTriggered = false
}

const refreshList = async () => {
  try {
    uni.showLoading()
    reset()
    await getDataList()
  } finally {
    uni.hideLoading()
  }
}
refreshList()
/** ----------- 分页加载 end --------- */
</script>

<template>
  <view class="common-page-bg">
    <scroll-view
      class="scroll-container"
      scroll-y
      refresher-enabled
      enable-back-to-top
      :refresher-triggered="scrollState.refresherTriggered"
      @refresherrefresh="onRefresherrefresh"
      @scrolltolower="getDataList"
    >
      <template v-if="scrollState.dataList.length">
        <view
          v-for="item in scrollState.dataList"
          :key="item.id"
          class="mb-24rpx flex items-center"
        >
          <view
            class="mr-24rpx"
            @click="toggleSelectItem(item)"
          >
            <image
              v-if="_selectedProgrammeList.includes(item.id)"
              class="w-32rpx h-32rpx"
              src="@/static/icons/check-active.png"
            ></image>
            <image
              v-else
              class="w-32rpx h-32rpx"
              src="@/static/icons/check-inactive.png"
            ></image>
          </view>
          <view class="px-32rpx rounded-16rpx bg-white mb-24rpx flex-1">
            <CommonActivityItem
              :title="item.name"
              :img-src="item.coverUrl"
              :desc-list="[
                { label: '节目类型', value: item.category_dictText },
                { label: '节目时长', value: `${item.duration}分钟` },
              ]"
              @custom-click="
                uniNavigateTo('/pages-sub/programme/detail/index?id=' + item.id)
              "
            />
          </view>
        </view>
        <wd-loadmore
          finished-text="没有更多了"
          :state="scrollState.loadState"
          @reload="getDataList"
        />
      </template>
      <wd-status-tip
        v-else
        image="content"
        tip="暂无内容"
      />
    </scroll-view>
    <BottomOperateBox>
      <view class="flex items-center">
        <view
          class="flex items-center flex-shrink-0 w-300rpx"
          @click="toggleSelectAll"
        >
          <template>
            <image
              v-if="isSelectedAll"
              class="w-32rpx h-32rpx mr-16rpx"
              src="@/static/icons/check-active.png"
            ></image>
            <image
              v-else
              class="w-32rpx h-32rpx mr-16rpx"
              src="@/static/icons/check-inactive.png"
            ></image>
          </template>
          <view class="chose-all">
            <text class="chose-all-active">
              {{ isSelectedAll ? '取消全选' : '全选' }}
            </text>
            <text>
              （{{ _selectedProgrammeList.length }}/{{ MAX_PROGRAMME_COUNT }}）
            </text>
          </view>
        </view>
        <wd-button
          custom-class="common-main-btn"
          @click="handleNext"
        >
          下一步
        </wd-button>
      </view>
    </BottomOperateBox>
  </view>
</template>

<style lang="scss" scoped>
.common-page-bg {
  position: relative;
  display: flex;
  flex-direction: column;
  height: 100vh;
}

.scroll-container {
  padding: 24rpx 24rpx 160rpx 24rpx;
  box-sizing: border-box;
}

.chose-all {
  font-size: 28rpx;
  color: $uni-text-color-grey;

  &-active {
    color: #f98f18;
  }
}
</style>
